package com.test.web.jdbc;

import com.test.web.jdbc.exception.JdbcException;
import lombok.Data;
import lombok.Getter;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * com.test.web.jdbc
 *
 * @author 白雨浓
 * date: 2018/10/21 11:16
 * content:
 */
@Getter
public class JdbcConnection {

    private static final String DRIVER = "com.mysql.jdbc.Driver";
    private static final String BASE_URL = "jdbc:mysql://%s:%d/%s?useUnicode=true&characterEncoding=UTF-8&useSSL=true";

    private String host = "localhost";
    private Integer port = 3306;
    private String database;
    private String username;
    private String password;

    private Connection connection;

    public JdbcConnection(String database, String username, String password) {
        this.database = database;
        this.username = username;
        this.password = password;
        this.connection = this.init();
    }

    public JdbcConnection(String host, Integer port, String database, String username, String password) {
        this.host = host;
        this.port = port;
        this.database = database;
        this.username = username;
        this.password = password;
        this.connection = this.init();
    }

    private Connection init() {
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            throw new JdbcException("no mysql driver");
        }

        String url = String.format(BASE_URL, this.host, this.port, this.database);

        try {
            return DriverManager.getConnection(url, this.username, this.password);
        } catch (SQLException e) {
            throw new JdbcException("Connection fail: " + e.getMessage());
        }
    }

    public void close() {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }


}
